﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommonExtensions.ObjectExtensions;
using CommonExtensions.StringExtensions;
using DBMigrator.Core.DbObjects.ForeignKey;
using StructureMap;

namespace DBMigrator.Core.DbObjects.Column
{
    public class AddColumn<T> : IAddColumn<T>
    {
        public string Name { get; protected set; }
        public uint Length { get; protected set; }
        public bool IsPrimaryKey { get; protected set; }
        public IForeignKey ForeignKey { get; protected set; }

        public Type SqlGenerationType
        {
            get { return typeof(IAddColumn); }
        }

        public Type Type
        {
            get { return typeof (T); }
        }

        public AddColumn(string name)
        {
            if (name.IsBlank())
                throw new ArgumentNullException("name");

            Name = name;
        }

        public AddColumn(string name, uint length)
            : this(name)
        {
            if(length == 0)
                throw new ArgumentException("length must be greater than zero", "length");

            Length = length;
        }

        public IAddColumn<T> SetAsPrimaryKey()
        {
            IsPrimaryKey = true;
            return this;
        }

        public IAddColumn<T> References(string primaryKeyTable, string primaryKeyColumn)
        {
            if(primaryKeyTable.IsBlank())
                throw new ArgumentNullException("primaryKeyTable");
            if(primaryKeyColumn.IsBlank())
                throw new ArgumentNullException("primaryKeyColumn");

            ForeignKey = ObjectFactory.With("primaryKeyTableName").EqualTo(primaryKeyTable)
                .With("primaryKeyColumnName").EqualTo(primaryKeyColumn).GetInstance<IAddForeignKey>();
            return this;
        }
    }
}
